<?php


namespace app\cms\admin\controller;

use app\cms\community\lib\statisticsModel;
use app\cms\model\merchant\goods\goodsModel;
use app\cms\model\merchant\merchantModel;
use app\cms\model\userModel;
use iflow\auth\Authorize\AuthAnnotation;
use iflow\Response;
use iflow\Router\Controller;
use iflow\Router\implement\Request\GetMapping;

#[Controller('%cmsAdmin%/statistics')]
class statistics {
    protected array $models = [
        // 统计用户
        'user' => userModel::class,
        // 统计商品
        'goods' => goodsModel::class,
        // 统计商户
        'merchant' => merchantModel::class
    ];
    protected string $model = "";

    public function __construct() {
        $type = request() -> params('type');
        if (isset($this->models[$type])) {
            $this->model = $this->models[$type];
        }
    }

    /**
     * 统计模型数据
     * @param string $startTime 开始时间
     * @param string $endTime 结束时间
     * @param string $type 统计日期类型
     * @param int $user_group_id 用户id
     * @return Response
     */
    #[GetMapping]
    #[AuthAnnotation('statistics', 'statisticsReadWrite|statisticsRead')]
    public function statistics(string $startTime, string $endTime, string $type = "day", int $user_group_id = 0): Response
    {
        if ($this->model === "")
            return message() -> nodata('请选择需要统计的数据类型');
        try {
            $statistics = (new statisticsModel($this->model))
                ->setStartTime($startTime)
                ->setEndTime($endTime);

            if ($user_group_id > 0 && request() -> params('type') === 'user') {
                $statistics -> setWhere([
                    'user_group_id' => $user_group_id
                ]);
            }
            return $statistics -> setType($type)
                -> statisticsInc();
        } catch (\Exception $e) {
            return message() -> parameter_error($e -> getMessage());
        }
    }
}